import tkinter as tk
from tkinter import filedialog
from tkinter import scrolledtext
from read import baiduOCR_print
import glob

'''打开选择文件夹对话框'''
root = tk.Tk()

isExist = False
isFile = False
# root.withdraw()
# img = Image.open('三笠.jpg')
# width = 400
# height = 400
# new_img = img.resize((width, height), Image.BILINEAR)
# new_img.save('wife.ico')
root.iconbitmap('wife.ico')
root.title("图片文字识别")
# 第2步，给窗口的可视化起名字
# window.title('My Window')
# 第3步，设定窗口的大小(长 * 宽)
# root.geometry('800x600')  # 这里的乘是小x
line_text_width = 110

# def change(event):
#         global line_text_width
#         line_text_width2 = math.ceil(root.winfo_width()/8)
#         if line_text_width != line_text_width2:
#             print('a'+str(line_text_width))
#             line_text2 = tk.Text(root, height=2, width=line_text_width2)
#             line_text2.grid(row=0, columnspan=2)

alert_text = tk.Label(root, height=2, text='图片中的文字需要保持竖直\n选择文件夹时会处理文件夹中所有文件，时间较长', font=('Arial', 12), bg='yellow', fg='red', width=80)
alert_text.grid(row=1, columnspan=3)
line_text = tk.Label(root, height=2, bg='gray', width=line_text_width)
line_text.grid(row=2, columnspan=3)


def choose_Folder():
    global isExist
    global isFile
    Folder_path = filedialog.askdirectory()  # 获得选择好的文件夹
    line_text.config(text=Folder_path)
    isExist = True
    isFile = False


def choose_File():
    global isExist
    global isFile
    Filepath = filedialog.askopenfilename()  # 获得选择好的图片
    line_text.config(text=Filepath)
    isExist = True
    isFile = True


b1 = tk.Button(root, text='选择图片所在文件夹', font=('Arial', 12), width=20, height=1, command=choose_Folder)
b1.grid(row=3, column=0)  # 第6步，主窗口循环显示
b2 = tk.Button(root, text='选择图片', font=('Arial', 12), width=20, height=1, command=choose_File)
b2.grid(row=3, column=1)  # 第6步，主窗口循环显示


def game_Start(path):
    if path:
        if isFile:
            line_text2.delete('1.0', 'end')
            gameOver(path)
        else:
            line_text2.delete('1.0', 'end')
            for picfile in glob.glob(path+"/*"):
                gameOver(picfile)


def gameOver(path):
    message1 = baiduOCR_print(path)
    line_text2.insert('end', "-" * 100 + '\n')
    for text in message1.get('words_result'):
        line_text2.insert('end', text.get('words') + '\n')


b3 = tk.Button(root, text='确认', font=('Arial', 12),
               bg='gray', width=20, height=1, command=lambda: game_Start(line_text.cget('text')))
b3.grid(row=3, column=2)
# print('Folder_path:', Folder_path)
# print('Filepath:', Filepath)
line_text2 = scrolledtext.ScrolledText(root, height=35, width=line_text_width)
line_text2.grid(row=4, columnspan=3)
root.mainloop()
